<template>
  <div v-if="isUser" class="login-image">
    <div>
      <van-cell-group inset style="margin-top: 60px;  flex-grow: 1;  ">
        <van-field
          v-model="userName"
          required
          label="用户名"
          placeholder="请输入用户名"
          style="font-size:18px;line-height:30px;"
        />
      </van-cell-group>
      <img src="/开始答题.png" style="width:50%; margin-top:20px" @click="login" />
    </div>
  </div>
  <div class="scroll-container">
    <div class="index">
      <div>
        <div class="form">
          <van-row justify="center">
            <strong>
              <label for="name">{{ title }}</label>
            </strong>
          </van-row>
        </div>
      </div>
      <div class="box">
        <div class="container">
          <img
            width="100"
            style="margin-left: 40px;"
            :src="mode === 0 ? '../单选题.png' : '../多选题.png'"
            alt
          />
          <div class="descr">
            <label for="description" style="line-height:5px; font-size:larger; ">{{ description }}</label>
          </div>
          <div class="image" v-if="isImage">
            <img width="250" height="200" :src="image" />
          </div>
          <div class="wrapper">
            <van-checkbox-group
              checked-color="#9b0000"
              v-model="checked"
              :max="maxOptions"
              class="van-checkbox-group"
              :class="wrapperClass"
              @change="handleChange"
            >
              <van-cell-group inset style="border-bottom-color: black;">
                <van-cell
                  v-for="(item, index) in optionsList"
                  clickable
                  :key="item"
                  :title="`${item}`"
                  @click="toggle(index)"
                  style="text-align:left;font-size:18px;line-height:30px;font-family:'Microsoft YaHei'; font-weight:500; "
                >
                  <template #right-icon>
                    <van-checkbox
                      :name="item"
                      :ref="el => checkboxRefs[index] = el"
                      @click.stop
                      icon-size="20px"
                      style="background-color:'#9b0000'"
                    />
                  </template>
                </van-cell>
              </van-cell-group>
            </van-checkbox-group>
          </div>
        </div>
        <div>
          <img width="270" style="margin-top: 80px;" src="/提交.png" @click="handle" />
        </div>

        <div v-if="isUser">
          <van-cell-group
            inset
            style="margin-top: 40px;margin-left:20px;margin-right:20px; flex-grow: 1; "
          >
            <van-field
              v-model="userName"
              required
              label="用户名"
              placeholder="请输入用户名"
              style="font-size:18px;line-height:30px;"
            />
          </van-cell-group>
        </div>
      </div>
      <div>
        <van-toast v-model="show" style="padding: 0">
          <template #message>
            <van-image :src="image" width="200" height="140" style="display: block" />
          </template>
        </van-toast>
      </div>
    </div>
  </div>
</template>

<script setup>
import { showToast } from "vant";
import { ref, reactive, onBeforeUpdate, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { useStore } from "vuex";

const store = useStore();
const isUser = ref(false);
const title = ref("");
const description = ref("");
const checked = ref([]);
const optionsList = reactive([
  { value: "option1", label: "A. " },
  { value: "option2", label: "B. " },
  { value: "option3", label: "C. " },
  { value: "option4", label: "D. " }
]);
const questionId = ref();
const checkboxRefs = ref([]);
const userName = ref("");
const show = ref(false);
const router = useRouter();
const toggle = index => {
  checkboxRefs.value[index].toggle();
};
const answer = ref(null);
const mode = ref(false);
const maxOptions = ref(1);
const userCookie = ref("");
const isImage = ref(false);
const imageBefore = ref("");
const image = ref("");

//复选框样式的计算属性
const wrapperClass = computed(() => {
  return isImage.value
    ? "option-wrapper-with-image"
    : "option-wrapper-without-image";
});
let routeParams = router.currentRoute.value.params;

onMounted(() => {
  store.commit("setQid", routeParams.qid);
  userCookie.value = getCookie("userName");
  if (userCookie.value) {
    console.log("Cookie存在:" + userCookie.value);
    isUser.value = false;
  } else {
    console.log("Cookie不存在");
    isUser.value = true;
  }

  axios
    .post("http://192.168.137.1:8080/museums/userAnswer/getQuestionInfo", {
      questionId: routeParams.qid
    })
    .then(res => {
      if (res) {
        if (res.data.currentQuestion.image !== "0") {
          isImage.value = true;
        }
        title.value = res.data.currentQuestion.title;
        description.value = res.data.currentQuestion.description;
        res.data.currentQuestion.option1 =
          "A. " + res.data.currentQuestion.option1;
        res.data.currentQuestion.option2 =
          "B. " + res.data.currentQuestion.option2;
        res.data.currentQuestion.option3 =
          "C. " + res.data.currentQuestion.option3;
        res.data.currentQuestion.option4 =
          "D. " + res.data.currentQuestion.option4;
        // optionsList.option1 = res.data.data.question
        optionsList[0] = res.data.currentQuestion.option1;
        optionsList[1] = res.data.currentQuestion.option2;
        optionsList[2] = res.data.currentQuestion.option3;
        optionsList[3] = res.data.currentQuestion.option4;
        answer.value = res.data.currentQuestion.answer;
        mode.value = res.data.currentQuestion.status;
        imageBefore.value = res.data.currentQuestion.image;
        image.value = "../" + imageBefore.value;

        //判断单选多选，设置可选数量
        // if (mode.value === 0) {
        //   maxOptions.value = 1;
        // } else {
        //   //无限制
        //   maxOptions.value = 0;
        // }
        maxOptions.value = 0;
      }
    });
});

const login = () => {
  setCookie("userName", userName, 1);
  // if (routeParams.qid == 1) {
  //   setCookie("firstQuestion", 1, 1);
  // }
};

onBeforeUpdate(() => {
  checkboxRefs.value = [];
});

//创建cookie
const setCookie = (name, value, days) => {
  // 获取当前时间
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); // 一天
  // date.setTime(date.getTime() + days * 3 * 60 * 1000); //一分钟
  const expires = "expires=" + date.toUTCString();
  //转码
  value = window.encodeURIComponent(value);
  document.cookie = name + "=" + value + ";" + expires + ";path=/";
  isUser.value = false;
};

//获取cookie
const getCookie = name => {
  const cookieName = name + "=";
  const cookies = document.cookie.split(";");
  for (let i = 0; i < cookies.length; i++) {
    let cookie = cookies[i];
    while (cookie.charAt(0) === " ") {
      cookie = cookie.substring(1);
    }
    if (cookie.indexOf(cookieName) === 0) {
      return window.decodeURIComponent(
        cookie.substring(cookieName.length, cookie.length)
      );
      // const decodedCookie = window.decodeURIComponent(cookie.substring(cookieName.length, cookie.length))
      // return window.JSON.parse(decodedCookie)
    }
  }
  return "";
};

const handle = () => {
  //有cookie执行以下操作
  if (userCookie.value) {
    if (checked.value.length === 0) {
      showToast("请选择选项!");
      return;
    }
    //把选中的选项进行拆解再合并成一个字符串
    const lastChecked = checked.value.map(value => value[0]).join("");
    axios
      .put("http://192.168.137.1:8080/museums/userAnswer", {
        questionId: routeParams.qid,
        currentUserName: userCookie.value,
        userAnswer: lastChecked
      })
      .then(res => {
        if (res.data.flag == "success") {
          router.push({
            path: "/answer1"
            // state: {qid : routeParams.qid}
          });

          return;
        }
        if (res.data.flag == "error") {
          router.push("/answer2");
          return;
        }
      });
    // if (lastChecked == res.data.currentQuestion.answer) {
    //     router.push("/answer1");
    //         return
    // } else{
    //     router.push("/answer2");
    //         return
    // }
  }
  //没有cookie执行的方法
  else {
    if (!checked.value.length || !userName.value) {
      showToast("请填写完整!");
      return;
    }
    setCookie("userName", userName.value, 1);
    const lastChecked = checked.value.map(value => value[0]).join("");

    axios
      .post("http://192.168.137.1:8080/museums/userAnswer/add", {
        questionId: routeParams.qid,
        currentUserName: userName.value,
        userAnswer: lastChecked
      })
      .then(res => {
        console.log(res);
        if (res.data.flag == "success") {
          router.push("/answer1");
          return;
        }
        if (res.data.flag == "error") {
          router.push("/answer2");
          return;
        }
      });
    // if (lastChecked == res.data.currentQuestion.answer) {
    //     router.push("/answer1");
    //         return
    // } else{
    //     router.push("/answer2");
    //         return
    // }
  }
};
</script>
  
<style lang="less" scoped>
.scroll-container {
  position: absolute;
  /* 添加绝对定位 */
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  /* 允许纵向滚动 */
}

.index {
  height: 150%;
  display: flex;
  flex-direction: column;
  background-image: url(/src/assets/newImages/红色答题背景图.jpg);
  background-size: 100% 100%;
}

.van-checkbox-border-color {
  border-bottom-color: black;
}
.login-image {
  background-image: url(/src/assets/newImages/登录页.jpg);
  background-size: 100% 100%;
  z-index: 1;
  height: 100vh;
  position: absolute;
  top: 0%;
  bottom: 0%;
  left: 0%;
  right: 0%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form {
  display: inline-block;
  white-space: nowrap;
  width: 80%;
  height: 70px;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 25px;
  margin-left: 20px;
  margin-right: 20px;
  font-size: 40px;
  color: #ffffff;
}

.wrapper {
  display: flex;
  flex-direction: column;
}

.van-checkbox-group {
  border-color: black !important;
  margin-top: 30px;
  margin-left: 15px;
  margin-right: 15px;
}

//当有图片时使用的样式
.option-wrapper-with-image {
  margin-top: 500px;
  margin-left: 15px;
  margin-right: 15px;
}

//没有图片时使用的样式
.option-wrapper-without-image {
  margin-top: 30px;
  margin-left: 15px;
  margin-right: 15px;
}

.descr {
  font-family: "Microsoft YaHei";
  display: inline-block;
  width: 80%;
  height: 10px;
  margin-top: 10px;
  margin-left: 80px;
  line-height: 1.8;
  margin-bottom: 20%;
  text-align: left;
  font-size: 30px;
  font-weight: bold;
  color: black;
}

.box {
  height: 80%;
  width: 90%;
  background-color: #ffffff;
  border-radius: 50px;
  margin-left: 5%;
}

.container {
  position: relative;
  flex-shrink: 0;
  margin-top: 10%;
  text-align: left;
}

.image {
  margin-top: 5%;
  position: absolute;
  margin-left: 20%;
}
</style>
   